<?php

namespace App\Models;


use App\Models\User;

class TopicOperationLog extends Model
{
    const TYPE_MOVE_FORUM = 1;
    const TYPE_DELETE = 2;
    const TYPE_RESTORE = 3;
    const TYPE_CHANGE_SENSITIVITY = 4;
    const TYPE_SET_STICKY = 5;
    const TYPE_CANCEL_STICKY = 6;

    public static $typeName = [
        self::TYPE_MOVE_FORUM => '转移',
        self::TYPE_DELETE => '删除',
        self::TYPE_RESTORE => '恢复',
        self::TYPE_CHANGE_SENSITIVITY => '修改敏感度',
        self::TYPE_SET_STICKY => '设置置顶',
        self::TYPE_CANCEL_STICKY => '取消置顶',
    ];

    protected $fillable = ['tid', 'type', 'uid', 'username', 'remarks', 'extra', 'deadline'];

    public static function booted()
    {
        static::creating(function (Model $model) {
            $admin = auth_user();
            $model->uid = $admin->id;
            $model->username = $admin->username;
            $model->request_id = REQUEST_ID;
            $model->is_latest = 1;
        });
        static::created(function (Model $model) {
           self::query()->where('tid', $model->tid)->where('id', '<', $model->id)->update(['is_latest' => 0]);
        });
    }

    public function getTypeNameAttribute()
    {
        return self::$typeName[$this->type] ?? '';
    }

    public function getExtraAttribute($value)
    {
        return json_decode($value, true);
    }

    public function setExtraAttribute($value)
    {
        if (is_array($value)) {
            $this->attributes['extra'] = json_encode($value, 336);
        }
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'uid');
    }


}
